package com.gitee.cui.netty.protocol;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * ProtoBuf编解码器客户端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/26 15:41
 **/
public class ProtoBufSendClient {

    private String serverIp;

    private int serverPort;

    private Bootstrap bootstrap = new Bootstrap();

    private final String content = "测试内容";

    public ProtoBufSendClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public static void main(String[] args) {
        new ProtoBufSendClient(NettyDemoConfig.SOCKET_SERVER_IP, NettyDemoConfig.SOCKET_SERVER_PORT).runClient();
    }

    /**
     * 启动客户端
     */
    private void runClient() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(worker);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                    ch.pipeline().addLast(new ProtobufEncoder());
                }
            });
            ChannelFuture future = bootstrap.connect(serverIp, serverPort);
            future.sync();

            Channel channel = future.channel();
            // 发送ProtoBuf对象数据
            for (int i = 0; i < 1000; i++) {
                MsgProtos.Msg msg = build(i, i + "->" + content);
                channel.writeAndFlush(msg);
                Logger.info("发送报文数：" + i);
            }
            channel.flush();

            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

    private MsgProtos.Msg build(int i, String s) {
        MsgProtos.Msg.Builder builder = MsgProtos.Msg.newBuilder();
        builder.setId(i);
        builder.setContent(s);
        return builder.build();
    }
}
